package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuditServiceImpl implements IAuditService {

    @Autowired
    @Lazy
    private IWmNewsService wmNewsService;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private IWmChannelService wmChannelService;

    @Override
    public void audit(Integer newsId) {
        WmNews wmNews = wmNewsService.getById(newsId);
        audit(wmNews);
    }

    @Override
    @Async
    public void audit(WmNews wmNews) {
        //审核自媒体文章的文本内容
        boolean isPass = true;
        //自管理敏感词的审核
        isPass = checkSensitive(wmNews);
        isPass = checkText(wmNews);
        if(!isPass) return;
        //审核自媒体文章的图片内容
        isPass = checkImage(wmNews);
        if(!isPass) return;
        //审核通过  feign远程调用 保存apArticle
        //判断是否现在已经达到发布时间
        //如果当前时间>发布时间，就意味着已经达到发布时间
        if(System.currentTimeMillis() > wmNews.getPublishTime().getTime()){
           // feign远程调用 保存apArticle
            Long articleId= saveApArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(9);
            wmNewsService.updateById(wmNews);
        }else{
           //只修改一下状态
            wmNews.setStatus(8);
            wmNewsService.updateById(wmNews);
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("news-dqueue");
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            long time = wmNews.getPublishTime().getTime()-System.currentTimeMillis();
            delayedQueue.offer(wmNews.getId(), time, TimeUnit.MILLISECONDS);
            log.info("延迟消息发送成功，预计在"+time+"秒后，会执行某一个方法"+new Date());
        }
    }

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IWmSensitiveService wmSensitiveService;

    private boolean checkSensitive(WmNews wmNews) {
        List<WmSensitive> wmSensitiveList = wmSensitiveService.list();
        List<String> stringList = wmSensitiveList.stream().map(s -> s.getSensitives()).collect(Collectors.toList());
        SensitiveWordUtil.initMap(stringList);
        String text = wmNews.getTitle();
        String content = wmNews.getContent();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text+= contentDto.getValue();
            }
        }
        Map<String, Integer> matchWordsMap = SensitiveWordUtil.matchWords(text);
        if(matchWordsMap.size()==0){
            return true;
        }else{
            wmNews.setStatus(2);
            Set<String> strings = matchWordsMap.keySet();
            String reason = String.join(",", strings);
            wmNews.setReason("敏感词审核不通过，原因是："+reason);
            wmNewsService.updateById(wmNews);
            return false;
        }

    }

    //远程发布app文章
    public Long saveApArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        dto.setContent(wmNews.getContent());
        //dto.setId();
        dto.setTitle(wmNews.getTitle());
        //自媒体用户中是有app文章作者
        //根据当前自媒体人的ID查询自媒体人对象
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        dto.setAuthorId(wmUser.getApAuthorId()); //app文章作者id
        dto.setAuthorName(wmUser.getName());
        dto.setChannelId(wmNews.getChannelId());
        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        dto.setChannelName(wmChannel.getName());
        dto.setLayout(wmNews.getType());
        dto.setFlag(0);  //文章标记            0 普通文章            1 热点文章            2 置顶文章            3 精品文章
        String images = wmNews.getImages();
        List<ImageDto> imageDtoList = JSON.parseArray(images, ImageDto.class);
        List<String> urlList = new ArrayList<>();
        for (ImageDto imageDto : imageDtoList) {
            urlList.add(imageDto.getUrl());
        }
        dto.setImages(String.join(",",urlList));
        dto.setLabels(wmNews.getLabels());
        dto.setPublishTime(wmNews.getPublishTime());
        return articleFeign.saveApArticle(dto).getData();
    }
    private boolean checkImage(WmNews wmNews) {
        //审核的内容中包含：1、文章封面图片 2、文章内容中的图片
        //文章封面图片
        List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        String content = wmNews.getContent();
        // " [{"type":"text","value":"自古人生有三大喜事"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/92f3fff2-b7ec-4ade-8798-40c896320c18.jpeg","id":267},
        //{"type":"text","value":"同学高考查询分数为0分，是怎么回事？"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/4e342011-dd0c-4a5b-8005-ad065ab43056.jpeg","id":264},
        //{"type":"text","value":"为保护考生隐私，出现“高考屏蔽生”"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/5ab971f2-8833-4d3f-8842-6848b7c6d50a.jpeg","id":266}]"
        //从文章内容中获取所有的图片，构建到一个List集合中
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                if(!imageDtoList.contains(imageDto)){
                    imageDtoList.add(imageDto);
                }
            }
        }
        try {
            List<byte[]> imageList = new ArrayList<>();
            //图片的下载，下载后上传到阿里云审核
            for (ImageDto imageDto : imageDtoList) {
                InputStream inputStream = minIOService.download(imageDto.getUrl());
                byte[] bytes = IOUtils.toByteArray(inputStream);// IOUtils是Apache的
                imageList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            //- pass：文本正常，可以直接放行。
            //- review：文本需要进一步人工审核。
            //- block：文本违规，可以直接删除或者限制公开
            switch (suggestion){
                case "pass":{
                    return true;
                }
                case "review":{
                    //修改自媒体文章的状态和原因
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核需要人工介入，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    //修改自媒体文章的状态和原因
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核不通过，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean checkText(WmNews wmNews) {
        //审核的内容中包含：1、文章标题 2、文章内容中的文本
        String text = wmNews.getTitle();
        String content = wmNews.getContent();
        // " [{"type":"text","value":"自古人生有三大喜事"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/92f3fff2-b7ec-4ade-8798-40c896320c18.jpeg","id":267},
        //{"type":"text","value":"同学高考查询分数为0分，是怎么回事？"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/4e342011-dd0c-4a5b-8005-ad065ab43056.jpeg","id":264},
        //{"type":"text","value":"为保护考生隐私，出现“高考屏蔽生”"},
        //{"type":"image","value":"http://192.168.85.143:9000/heima/5ab971f2-8833-4d3f-8842-6848b7c6d50a.jpeg","id":266}]"
        //从文章内容中获取所有的图片，构建到一个List集合中
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text+= contentDto.getValue();
            }
        }
        try {
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            // pass：文本正常，可以直接放行。
            // review：文本需要进一步人工审核。
            // block：文本违规，可以直接删除或者限制公开
            switch (suggestion){
                case "pass":{
                    return true;
                }
                case "review":{
                    //修改自媒体文章的状态和原因
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核需要人工介入，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    //修改自媒体文章的状态和原因
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核不通过，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}